// 配置模板引擎
if (typeof window.swig !== undefined) {

  // 时区: 东八区
  swig.setDefaultTZOffset(-480);

  // 转换数字
  swig.setFilter('number', function (input) {
    return Number(input);
  });

  // 保留小数
  swig.setFilter('toFixed', function (input, count) {
    return Number(input).toFixed(count);
  });

  // 格式化金额
  swig.setFilter('currency', function (input, size, symbol) {
    return input === undefined ? '' : (symbol || '￥') + Number(input).toFixed(size === undefined ? 2 : size);
  });

  // 截取字符串
  swig.setFilter('truncate', function (input, size) {
    input = String(input || '');
    if (input.length <= size) {
      return input;
    }
    return input.substring(0, size) + '...';
  });

  // 七牛缩略图服务
  swig.setFilter('thumb', function (uri, width, height) {
    uri = uri || '/assets/images/opacity.png';
    if (uri.indexOf('?') === -1) {
      uri = uri + '?imageView2/2/w/' + width + '/h/' + height;
    }
    return uri;
  });

  // 跳转模型
  swig.setFilter('skipModel', function (model) {
    // 转换JSON
    if (typeof model === 'string') {
      model = JSON.parse(model);
    }
    var data = model.entity;
    switch (data.skno) {
    case 1000:
      return '/home';
    case 1001:
      return '/home';
    case 1002:
      return '/assistant/notices';
    case 2000:
      return '/assistant';
    case 4000:
      return '/profile';
    case 4001:
      return '/account/orders';
    case 4002:
      return '/account/addresses';
    case 4003:
      return '/shopping/cart';
    case 4008:
      return '/shopping/order/' + data.id;
    case 4009:
      return '/shopping/order/' + data.id;
    case 4100:
      return '/wallet';
    case 4101:
      return '/wallet/records';
    case 4102:
      return '/wallet/deposit';
    case 4104:
      return '/account/coupons';
    case 4105:
      return '/wallet/manage';
    case 4200:
      return '/settings';
    case 4204:
      return '/account/mobile';
    case 5000:
      return '';
    case 5001:
      return '';
    case 5002:
      return '';
    case 5003:
      return '';
    case 5004:
      return '/shopping/details/' + data.id;
    case 5005:
      return '';
    case 5006:
      return '/shopping';
    case 7000:
      return data.url;
    }
    return '#install';
  });
}

// 客户端桥接文件
(function (global) {

  // 连接服务器
  function connect(callback) {
    if (window.WebViewJavascriptBridge) {
      callback(WebViewJavascriptBridge);
    }
    else {
      document.addEventListener('WebViewJavascriptBridgeReady', function () {
        callback(WebViewJavascriptBridge);
      }, false);
    }
  }

  // 初始化并获取句柄
  connect(function (bridge) {
    // 不能删除
    bridge.init(function (message, callback) {});

    // 可以添加客户端方法
    bridge.registerHandler("webviewCallback", function (data) {
      data = typeof data === 'object' ? data : JSON.parse(data);
      // 点击菜单
      if (data.action === 'menuClick') {
        if (/^event:/.test(data.entity.content)) {
          $(document).triggerHandler(data.entity.content);
        }
        else {
          location.href = data.entity.content;
        }
      }
      // 扫码结果
      else if (data.action === 'scanResult') {
        $(document).triggerHandler('event:scanner', data);
      }
      // 支付回调
      else if (data.eventType === 'jsShowQDPay') {
        if (data.code == 200) {
          location.href = '/cashier/success?code=' + data.orderCode;
        }
        else {
          location.href = '/cashier/failure?code=' + data.orderCode;
        }
      }
    });
  });

  // 代理服务端行为
  global.ClientBridge = {

    // 构造菜单
    setMenus: function (list) {
      connect(function (bridge) {
        bridge.callHandler("jsShowMenuList", {
          menuList: list
        });
      });
    },

    // 支付接口
    payment: function (code, price, business) {
      // 如果不是APP
      if (!window.WebViewJavascriptBridge || navigator.userAgent.toLocaleLowerCase().indexOf('micromessenger') !== -1) {
        location.href = '/cashier/payment?code=' + code + '&business=' + business;
      }
      // 判断是APP
      else {
        window.WebViewJavascriptBridge.callHandler('jsShowQDPay', {
          orderId: code,
          shouldPay: price,
          payBusinessType: business
        });
      }
    },

    // 扫码
    scanner: function (type) {
      connect(function (bridge) {
        bridge.callHandler("jsShowGjScanner", {
          isGetReturnData: type || 0
        });
      });
    },

    // 关闭自身
    close: function () {
      connect(function (bridge) {
        bridge.callHandler("jsToolCloseWebPage", {});
      });
    },

    // 删除公告
    deleteNotice: function (id) {
      connect(function (bridge) {
        bridge.callHandler("jsDelGroupNotice", {
          billboardId: id
        });
      });
    },
  };

  // 快捷支付
  $(document).on('click', '[data-code][data-price][data-business]', function (e) {
    var data = $(this).data();
    ClientBridge.payment(data.code, data.price, data.business);
    return false;
  });

})(window);

// 权限拦截
$(document).on('ajaxSuccess', function (e, xhr, data, res) {
  if (res.code === 403) {
    Modal.confirm({
      message: '您需要登录之后才能操作',
      callback: function () {
        var agent = navigator.userAgent.toLowerCase();
        if (agent.indexOf('micromessenger') !== -1 || agent.indexOf('ali') !== -1) {
          return location.href = '/account/improve?next=' + encodeURIComponent(location.href);
        }
        return location.href = '/account/login?next=' + encodeURIComponent(location.href);
      }
    });
  }
});

/**
 * 通知
 */
(function () {
  var timer = null;
  var lasted = 4000;
  var instance = null;

  var notice = window.notice = function (message, type) {
    if (instance === null) {
      instance = $('<div class="js-notice" />').appendTo('body');
    }
    type = type || 'normal';
    instance.removeClass('overdue').html('<span class="' + type + '">' + message + '</span>');
    clearTimeout(timer);
    timer = setTimeout(function () {
      instance.addClass('overdue');
    }, lasted);
    return false;
  };

  // 添加快捷方式
  ['message', 'success', 'warning', 'failure'].forEach(function (name) {
    notice[name] = function (message) {
      notice(message, name);
    };
  });
})();

/**
 * 脚本组件都通过这个实例来创建
 */
(function () {
  // 缓存编译模板
  var cache = {};

  // 当前激活的实例
  var instance = null;

  var Template = window.Template = {

    // 编辑
    compile: function (selector, context) {
      var translate = cache[selector];
      if (!translate) {
        var fragment = selector;
        var container = $(selector)
        if (container.is('[type="text/swig-template"]')) {
          fragment = container.html();
        }
        cache[selector] = translate = swig.compile(fragment);
      }
      return translate(context).toString();
    },

    // 通过选择器编译
    render: function (selector, context, fn) {
      fn = fn || $.noop;
      this.remove();
      instance = $(this.compile(selector, context));
      $('body').append(instance);
      fn(instance, context);
      return instance;
    },

    // 隐藏
    hide: function () {
      if (instance) {
        instance.hide();
      }
    },

    // 移除
    remove: function () {
      if (instance) {
        instance.remove();
        instance = null;
      }
    },

    // 句柄
    getInstance: function () {
      return instance;
    }
  };

})();

/**
 * 弹窗控件
 */
(function (global) {
  var alertTempl = '\
    <div class="masklayer flexbox {% if mode %}mode{% endif %}">\
      <div class="modal">\
        <div class="wrap">\
          <h3 class="title text-center">{{ title|safe }}</h3>\
          <div class="content text-center">{{ message|safe }}</div>\
        </div>\
        <a class="footer" {% if url %}href="{{ url }}"{% endif %}>\
          <span class="text-blue">{{ confirmText|safe }}</span>\
        </a>\
      </div>\
    </div>';

  var confirmTempl = '\
    <div class="masklayer flexbox {% if mode %}mode{% endif %}">\
      <div class="modal">\
        <div class="wrap">\
          <h3 class="title text-center">{{ title|safe }}</h3>\
          <div class="content text-center">{{ message|safe }}</div>\
        </div>\
        <div class="footer">\
          <div class="button-group">\
            <button class="text-center button small square transparent text-blue" data-dismiss="true">{{ cancelText|safe }}</button>\
            <button class="text-center button small square transparent text-blue confirm">{{ confirmText|safe }}</button>\
          </div>\
        </div>\
      </div>\
    </div>';

  var loadingTempl = '\
      <div class="masklayer flexbox mode">\
        <div class="spinner-loader">loading</div>\
      </div>';

  // 默认文案
  var options = {
    title: '温馨提示',
    message: '千丁欢迎您',
    cancelText: '取消',
    confirmText: '确定',
    mode: false,
    callback: $.noop,
  };

  global.Modal = {

    alert: function (context, callback) {
      if (typeof context !== 'object') {
        context = {
          message: context
        };
      }
      if (typeof callback === 'function') {
        context.callback = callback;
      }

      context = $.extend({}, options, context);
      var widget = context.widget = Template.render(alertTempl, context);
      widget.on('click', '.footer', function () {
        if (context.callback() !== false && Template.getInstance() === widget) {
          Template.hide();
        }
      });

      return widget;
    },

    confirm: function (context, callback) {
      if (typeof context !== 'object') {
        context = {
          message: context
        };
      }
      if (typeof callback === 'function') {
        context.callback = callback;
      }
      context = $.extend({}, options, context);

      var widget = context.widget = Template.render(confirmTempl, context);
      widget.on('click', '.footer [data-dismiss]', function () {
        Template.hide();
      });
      widget.on('click', '.footer .confirm', function () {
        if (context.callback() !== false && Template.getInstance() === widget) {
          Template.hide();
        }
      });

      return widget;
    },

    loading: function (context, callback) {
      if (typeof context !== 'object') {
        context = {
          message: context
        };
      }

      context = $.extend({}, options, context);
      var widget = context.widget = Template.render(loadingTempl, context);
      return widget;
    }
  };

  global.install = function (message) {
    return Modal.confirm({
      message: message || '安装千丁小区应用体验此功能?',
      confirmText: '安装',
      callback: function () {
        location.href = "http://dl.qdingnet.com";
      }
    });
  };

  $(document).on('click', 'a[href="#install"]', function () {
    global.install();
    return false;
  });
})(window);

/**
 * 选项卡效果
 */
(function () {
  // 核心方法
  var tab = function (e) {
    var current = $(this);
    var previous = current.siblings('.item.active');
    // 隐藏前个TAB
    previous.removeClass('active');

    // 隐藏容器
    $(previous.attr('href')).removeClass('active');

    // 激活当前TAB
    current.addClass('active');
    $(current.attr('href')).addClass('active');
    if (e) {
      e.preventDefault();
    }
  };

  // 添加插件
  $.fn.tab = function () {
    return $(this).each(function () {
      tab.call(this);
      $(this).triggerHandler('click');
    });
  };

  // 全局代理
  $(document).on('click', '.tabs[data-tabs="true"] > .item', tab);
})();

/**
 * 下拉菜单效果
 */
(function () {
  $(document).on('click', function () {
    $('.dropdown').removeClass('active');
  });

  $(document.body).on('click', '.dropdown .toggle', function (e) {
    var dropdown = $(this).parents('.dropdown').eq(0);
    $('.dropdown').not(dropdown).removeClass('active');
    dropdown.toggleClass('active');
    e.stopPropagation();
  });

  $(document.body).on('click', '.dropdown .menubar', function (e) {
    setTimeout(function () {
      $(this).parents('.dropdown').removeClass('active');
    }.bind(this), 0);
    e.stopPropagation();
  });
})();

////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * 监听滚动回调 通常用于翻页
 */
(function (global) {

  var fns = [];

  // 给文档绑定滚动事件
  var addLisener = function () {
    // 滚动临界点
    var cordon = 1;
    // 防止重复请求
    var loading = false;
    var element = document.documentElement;
    $(document).on('scroll', function (e) {
      if (!loading) {
        var range = Math.max(element.scrollHeight - element.clientHeight, 0);
        var distance = range - document.body.scrollTop;
        if (range !== 0 && distance / element.clientWidth <= cordon) {
          loading = true;
          fireCallback().then(function (data) {
            loading = false;
            return data
          });
        }
      }
    });

    addLisener = $.noop;
  };

  // 调用注册回调
  var fireCallback = function () {
    // 添加loading文案
    if ($('section p.loadmore').length === 0) {
      $('section').append('<p class="loadmore">正在加载...</p>');
    }

    return new Promise(function (resolve, reject) {
      var num = fns.length;
      var list = [];
      fns.forEach(function (fn) {
        fn().then(function (res) {
          list.push(res);
          --num;
          if (num === 0) {
            resolve(list);
            // 移除loading文案
            $('section p.loadmore').remove();
          }
        });
      });
    });

  };

  // 添加滚动事件
  global.listenScroll = function (fn) {
    if (typeof fn === 'function' && fns.indexOf(fn) === -1) {
      fns.push(fn);
      addLisener();
    }
  };

  // 添加一个翻页模板函数
  global.loadMoreFactory = function (options) {
    // 加载更多分页
    var page = options.page || 1;
    var size = options.size || 10;
    // 是否执行
    var before = options.before || function () {
      return true;
    };
    var more = true; // 是否有更多数据

    // 第一个回调
    listenScroll(function () {
      return new Promise(function (resolve, reject) {
        if (more === false || !before()) {
          return resolve(null);
        }
        $.get(options.url, {
          page: ++page,
          size: size,
        }).then(function (res) {
          if (res.code === 200) {
            $(options.panel).append(Template.compile(options.template, res.data));
            more = res.data.list.length >= size;
          }
          resolve(res);
        });
      });
    });
  };

})(window);

// 动态添加或移除has-footer
(function () {
  $('body > section').toggleClass('has-footer', $('body > footer.bar').length);
})();

// 滑动焦点图
function swipe(selector) {
  var index = 0;
  var pages = null;
  var items = $(selector).find('.wrap > .item');
  var basis = $(selector).prop('offsetWidth');

  // 添加分页
  if (items.length > 1) {
    var frag = '';
    for (var i = 0; i < items.length; i++) {
      frag += '<a class=""></a>';
    }
    var foot = $('<div class="pages" />').html(frag);
    pages = foot.children();
    pages.eq(index).addClass('active');
    $(selector).append(foot);
  }

  // 设置容器宽度
  $(selector).find('.wrap').css('width', basis * items.length);

  // 设置元素宽度
  items.forEach(function (item) {
    $(item).css('width', basis);
  });

  // 移动效果
  var running = false;

  function move(index) {
    running = true;
    $('.swipe > .wrap').animate({
      left: -index * basis
    }, 400, 'ease-in-out', function () {
      running = false;
      pages.removeClass('active').eq(index).addClass('active');
    });
  }

  // 左移
  function move2left() {
    if (!running) {
      index = Math.min(index + 1, items.length - 1);
      move(index);
    }
  }

  // 右移
  function move2right() {
    if (!running) {
      index = Math.max(index - 1, 0);
      move(index);
    }
  }

  // 记录起始点
  var xDown = null;
  var yDown = null;

  // 移动判断
  function handleMove(evt) {
    evt.preventDefault();
    var xUp = evt.touches[0].clientX;
    var yUp = evt.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    // 水平移动
    if (Math.abs(xDiff) > Math.abs(yDiff) && Math.abs(xDiff) > 80) {
      if (xDiff > 0) {
        /* left swipe */
        move2left();
      }
      else {
        /* right swipe */
        move2right();
      }
    }
  }

  // 开始
  $(selector).on('touchstart', function (evt) {
    xDown = evt.touches[0].clientX;
    yDown = evt.touches[0].clientY;
    $(document).on('touchmove', handleMove);
  });

  // 结束
  $(document).on('touchend', function (evt) {
    $(document).off('touchmove', handleMove);
  });
}

(function () {
  $('[data-swipe="true"]').each(function () {
    swipe(this);
  });
})();
